package com.peiqi.aiproject.service;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Service
public class MessageService {
    @Value("${ai.api-key}")
    private String appKey;
    @Resource
    private Generation generation;

//    WebSocket方式流式输出AI
    public void sendMessage(String question) {
//        chatHandler.sendMessage(question);
//        // 构建用户消息
//        Message message = Message.builder()
//                .role(Role.USER.getValue())
//                .content(question).build();
//
//        // 设置AI对话参数
//        QwenParam qwenParam = QwenParam.builder()
//                .model(Generation.Models.QWEN_PLUS)
//                .messages(Collections.singletonList(message))
//                .topP(0.8)
//                .resultFormat(QwenParam.ResultFormat.MESSAGE)
//                .enableSearch(true)
//                .apiKey(appKey)
//                .incrementalOutput(true)
//                .build();
//        Semaphore semaphore = new Semaphore(0);
//        StringBuilder fullContent = new StringBuilder();
//        // 调用AI生成服务
//        CompletableFuture.runAsync(() -> {
//            try {
//                generation.streamCall(qwenParam, new ResultCallback<GenerationResult>() {
//
//                    @Override
//                    public void onEvent(GenerationResult message) {
//                        fullContent
//                                .append(message.getOutput().getChoices().get(0).getMessage().getContent());
//                        chatHandler.sendMessageToUser("1",fullContent.toString());
//                        System.out.println(message);
//                    }
//
//                    @Override
//                    public void onError(Exception err) {
//                        System.out.println(String.format("Exception: %s", err.getMessage()));
//                        semaphore.release();
//                    }
//
//                    @Override
//                    public void onComplete() {
//                        System.out.println("Completed");
//                        semaphore.release();
//                    }
//
//                });
//            } catch (NoApiKeyException e) {
//                throw new RuntimeException(e);
//            } catch (InputRequiredException e) {
//                throw new RuntimeException(e);
//            }
//        }, Executors.newSingleThreadExecutor());
////        semaphore.acquire();
    }

    public Flowable<GenerationResult> sendMessageStream(String question) throws NoApiKeyException, InputRequiredException {
        // 构建用户消息
        Message message = Message.builder()
                .role(Role.USER.getValue())
                .content(question).build();

        // 设置AI对话参数
        QwenParam qwenParam = QwenParam.builder()
                .model(Generation.Models.QWEN_PLUS)
                .messages(Collections.singletonList(message))
                .topP(0.8)
                .resultFormat(QwenParam.ResultFormat.MESSAGE)
                .enableSearch(true)
                .apiKey(appKey)
                .incrementalOutput(true)
                .build();
        // 调用AI生成服务
         return generation.streamCall(qwenParam);
    }
}
